<template>
  <el-card header="登录页">
    <el-form
      ref="form"
      :model="user"
      :rules="rules"
      style="max-width: 800px"
      label-width="80px"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="user.userName"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="pwd">
        <el-input v-model="user.pwd"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">立即创建</el-button>
        <el-button>取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { doLogin } from '_api'
export default {
  data () {
    return {
      user: {
        userName: '',
        pwd: ''
      },
      rules: {
        userName: [
          {
            required: true,
            message: '用户名必须填写',
            trigger: 'blur'
          }
        ],
        pwd: [
          {
            required: true,
            message: '密码必须填写',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    onSubmit () {
      // 提交表单
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 发送请求新增商品即可
          doLogin(this.user).then(res => {
            if (res.data.code === 200) {
              // 缓存返回数据
              localStorage.setItem('token', res.data.data.token)
              localStorage.setItem('userInfo', JSON.stringify(res.data.data.userInfo))
              localStorage.setItem('role', res.data.data.userInfo.role)
              // 过滤侧边导航
              this.$store.commit('auth/FILTER_MENU', res.data.data.userInfo.role)
              this.$message({
                type: 'success',
                message: res.data.msg,
                duration: 2000,
                onClose: () => {
                  // 去admin页
                  this.$router.replace('/')
                }
              })
            }
          })
        } else {
          console.log('验证不通过!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
